﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Windows.Controls;
using System.Windows;

namespace Pavilion.NodeDesigner
{
    public class AnchorVisibilityManager
    {
        private ListBoxItem HitListBoxItem { get; set; }

        public void HitTestForAnchor(Visual locationInVisualTree, Point location)
        {
            var hitListBoxItem = ReturnHitListBoxItem(locationInVisualTree, location);
            if (HitListBoxItem == hitListBoxItem)
                return;

            TryMakeAnchorsInvisible(HitListBoxItem);

            HitListBoxItem = hitListBoxItem;
            TryMakeAnchorsVisible(HitListBoxItem);
        }

        private static ListBoxItem ReturnHitListBoxItem(Visual locationInVisualTree, Point location)
        {
            ListBoxItem listBoxItem = null;
            VisualTreeHelper.HitTest(locationInVisualTree, null,
                hitTestParameters: new PointHitTestParameters(location),
                resultCallback: result =>
                {
                    listBoxItem = NewWayHelper.GetAncestor(result.VisualHit, typeof(ListBoxItem)) as ListBoxItem;

                    return HitTestResultBehavior.Stop;
                });

            return listBoxItem;
        }

        private static void TryMakeAnchorsInvisible(ListBoxItem listBoxItem)
        {
            try
            {
                if (listBoxItem != null)
                    (listBoxItem.Template.FindName("anchorGrid", listBoxItem) as Grid)
                         .Visibility = System.Windows.Visibility.Hidden;
            }
            catch { }
        }

        private static void TryMakeAnchorsVisible(ListBoxItem listBoxItem)
        {
            try
            {
                if (listBoxItem != null)
                    (listBoxItem.Template.FindName("anchorGrid", listBoxItem) as Grid)
                         .Visibility = System.Windows.Visibility.Visible;
            }
            catch { }
        }
    }
}
